$(function () {

    var appointId = $.getUrlParam('orderId');
    var userId = $.getUrlParam('user_id');
    var treatmentTime,treatmentPeriod,treatmentHospitalAddress,treatmentHospital,price ;

    // 当订单状态是抢号中时...点击编辑按钮...出现编辑就诊信息....
    $('.edit_registration_order').click(function () {

        $('.seeDoctor_info').hide();
        $('.editDoctor_info').show();
        $('.div_save').show();


        getDoctorHospital(720);
        var hospital_name = $('select.treatmentHospital option:selected').html();

        $('input.input_treatmentHospital').val(hospital_name);


    });

    // 保存所编辑的就诊信息出现弹框...
    $('.save_registration_info').click(function () {

        // 校验必填项不能为空...就诊时间
        if( $('.start_time').val() == '' ){
            $('.start_time').parent().siblings('div.tips').show()
            return false;
        }else{
            $('.start_time').parent().siblings('div.tips').hide()
        };
        // 校验必填项不能为空...就诊时间段
        if( $('.treatmentPeriod option:selected').html() == '' ){
            $('.treatmentPeriod').parent().siblings('div.tips').show()
            return false;
        }else{
            $('.treatmentPeriod').parent().siblings('div.tips').hide()
        };
        // 校验必填项不能为空...就诊医院
        if( $('.treatmentHospital option:selected').html() == '' ){
            $('.treatmentHospital').parent().siblings('div.tips').show()
            return false;
        }else{
            $('.treatmentHospital').parent().siblings('div.tips').hide()
        };
        // 校验必填项不能为空...就诊地址
        if( $('input.treatmentHospitalAddress').val() == '' ){
            $('input.treatmentHospitalAddress').parent().siblings('div.tips').show()
            return false;
        }else{
            $('input.treatmentHospitalAddress').parent().siblings('div.tips').hide()
        };
        // 校验必填项不能为空...就诊地址
        if( $('input.price').val() == '' ){
            $('input.price').parent().siblings('div.tips').show()
            return false;
        }else{
            $('input.price').parent().siblings('div.tips').hide()
        };

        // 出现弹框
        $('.mask-change').show();
        $('.confirm_order').show();

        // 将填写的信息放入弹框中展示...就诊信息
        $('span.bounce_time').html( getMoth($('.start_time').val()) );//就诊时间
        $('span.bounce_period').html( $('.treatmentPeriod option:selected').html() );//时间段
        $('span.bounce_orderNum').html( $('span.orderNo').html() );//订单编号
        $('span.bounce_price').html( $('input.price').val() );//医事服务费
        $('span.bounce_hospital').html( $('input.input_treatmentHospital').val() );//就诊医院
        $('span.bounce_address').html( $('input.treatmentHospitalAddress').val() );//就诊地址
        $('span.bounce_appoint').html( $('span.scheduleTime').html() );//预约时间

    });

    // 在弹框中点击确定...向后台提交表单信息..
    $('.sure_save_edit').click(function () {

        // 搜集表单信息...将表单信息提交给后台
        treatmentTime = $('.start_time').val();
        var timeStamp = new Date( treatmentTime ).getTime();
        var timeSecond = parseInt(timeStamp/1000)
        // console.log(timeStamp);
        treatmentPeriod = $('.treatmentPeriod option:selected').val();
        treatmentHospitalAddress = $('input.treatmentHospitalAddress').val();
        treatmentHospital = $('input.input_treatmentHospital').val();
        price = $('input.price').val();

        saveEditor(appointId,timeSecond,treatmentPeriod,treatmentHospitalAddress,treatmentHospital,price);

    });


    // 当订单状态是抢号中时...点击取消按钮...出现弹框...
    $('.cancel_registration_btn').click(function () {

        $('.mask-change').show();
        $('.cancel_registration_order').show();

    });

    // 日历插件初始化...
    $('.form_datetime_start').datetimepicker({
        //language:  'fr',
        weekStart: 1,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView:2,
        maxView:2,
        format: 'yyyy-mm-dd',
        linkField:"hidden_starttime",//值反射域
        linkFormat: "yyyy-mm-dd",
        // showMeridian: 1//是否显示上午下午...AM...PM...
    });

    // 页面初始化...
    showOrderDetail( appointId,userId );

    // 展示订单的信息...
    function showOrderDetail( appointId,userId ) {

        $.ajax({
            async: false,
            cache:false,
            headers: {"Accept-CMS-Token":token},
            type: 'post',
            url: appointditails,
            data: {
                appointId:appointId,
                userId:userId,
            },
            dataType: 'json',
            success: successFn,
            error: function () {
                console.log('预约挂号订单详情获取失败...')
            }
        });

    };

    // 向后台发送展示此条信息的ajax接口success时
    function successFn(data) {

        if(data.resultCode==200) {

            var value = data.value;

            // 首先判断这个订单是否是抢号订单
            if( value.appointType == 2 ){//是抢号订单...

                value = value.localAppointOrder;

                $('.orderStatus').html( changRegisOrderStatus(value.orderStatus,value.lifeType) );// 订单状态..

                console.log(changRegisOrderStatus(value.orderStatus,value.lifeType))

                // 当订单状态是抢号中的时候...显示编辑和隐藏两个按钮
                if(changRegisOrderStatus(value.orderStatus,value.lifeType) == '抢号中'){
                    $('.ed_margin').show();

                }else {
                    $('.ed_margin').hide();

                };

                // 医生信息
                if(value.urlHeader == '' || value.urlHeader == null){
                    $('.img_div img').attr('src','images/default.jpg');

                }else {
                    $('.img_div img').attr('src','http://res.1hudoctor.com/' + value.urlHeader + '.jpg');

                };
                $('span.doctor_name').html( value.consultantName );// ..姓名
                $('span.doctor_profn').html( value.rank );// ..在科室的职位
                $('span.doctor_office').html( value.deptName );// ..科室
                $('span.doctor_hospital').html( value.hospitalName );// ..医院

                // 患者信息
                $('span.patientName').html( value.patientName );// ..姓名
                $('span.patientPhone').html( value.patientPhone );// ..手机号
                $('span.idCard').html( value.idCard );// ..身份证号

                // 就诊信息
                $('span.treatmentTime').html( getMoth(Number(value.treatmentTime + '000')) );// ..就诊时间
                $('span.orderNo').html( value.orderNo );// ..订单编号
                $('span.price').html( value.price );// ..医事服务费
                $('span.treatmentHospital').html( value.treatmentHospital );// ..就诊医院
                $('span.treatmentHospitalAddress').html( value.treatmentHospitalAddress );// ..就诊地址
                $('span.scheduleTime').html( getMoth(value.createTime) );// ..预约时间
                $('span.payType').html( changePayType(value.payType) );// ..支付方式

            }else if( value.appointType == 1 ){//是正常流程订单

                $('.ed_margin').hide();

                var normalValue = value.localAppointOrder;
                var item = value.item;

                $('.orderStatus').html( changRegisOrderStatus(normalValue.orderStatus,normalValue.lifeType) );// 订单状态..

                // 医生信息
                if(value.urlHeader == '' || value.urlHeader == null){
                    $('.img_div img').attr('src','images/default.jpg');

                }else {
                    $('.img_div img').attr('src','http://res.1hudoctor.com/' + value.urlHeader + '.jpg');

                };
                $('span.doctor_name').html( normalValue.consultantName );// ..姓名
                $('span.doctor_profn').html( normalValue.rank );// ..在科室的职位
                $('span.doctor_office').html( normalValue.deptName );// ..科室
                $('span.doctor_hospital').html( normalValue.hospitalName );// ..医院

                // 患者信息
                $('span.patientName').html( normalValue.patientName );// ..姓名
                $('span.patientPhone').html( normalValue.patientPhone );// ..手机号
                $('span.idCard').html( normalValue.idCard );// ..身份证号

                // 就诊信息
                $('span.treatmentTime').html( getMoth(Number(normalValue.treatmentTime+'000')) );// ..就诊时间
                $('span.orderNo').html( normalValue.orderNo );// ..订单编号
                $('span.price').html( normalValue.price );// ..医事服务费
                $('span.treatmentHospital').html( normalValue.treatmentHospital );// ..就诊医院
                $('span.treatmentHospitalAddress').html( normalValue.treatmentHospitalAddress );// ..就诊地址
                $('span.scheduleTime').html( getMoth(  normalValue.createTime  ) );// ..预约时间
                $('span.payType').html( changePayType(normalValue.payType) );// ..支付方式

            }


        } else if(data.resultCode==515) {

            reLogin();

        } else {

            console.log('其它错误...')

        };


    };

    // 在取消挂号订单的弹框中..点击确定...
    $('.sure_cancel').click(function () {

        // 掉后台的接口...取消抢号订单
        $.ajax({
            async: false,
            cache:false,
            headers: {"Accept-CMS-Token":token},
            type: 'post',
            url: cancelappointorder,
            data: {
                appointId:appointId,
                userId:userId,
            },
            dataType: 'json',
            success: function (data) {
                if(data.resultCode==200) {

                    alert('取消成功!');
                    window.location.href = registration ;

                } else if(data.resultCode==515) {

                    reLogin();

                } else {
                    console.log('其他错误...')
                };
            },
            error: function () {
                console.log('取消挂号订单失败...')
            }
        })

    });

    function saveEditor(id,treatmentTime,treatmentPeriod,treatmentHospitalAddress,treatmentHospital,price) {

        $.ajax({

            async: false,
            cache:false,
            headers: {"Accept-CMS-Token":token},
            type: 'post',
            url: editappointorder,
            data: {
                id:id,
                treatmentTime:treatmentTime,
                treatmentPeriod:treatmentPeriod,
                treatmentHospitalAddress:treatmentHospitalAddress,
                treatmentHospital:treatmentHospital,
                price:price
            },
            dataType: 'json',
            success: function (data) {

                if(data.resultCode==200) {

                    alert('保存成功!')

                    window.location.href = registration ;

                } else if(data.resultCode==515) {

                    reLogin();

                } else {

                    console.log('其他错误...')
                };

            },
            error: function () {
                console.log(' 挂号订单编辑失败...')
            }
        });

    };

    // 当选医生所对应的医院时...地址跟随医院发生变化
    $('select.treatmentHospital').change(function () {

        var hospital_address = $('select.treatmentHospital option:selected').attr('address');
        var hospital_name = $('select.treatmentHospital option:selected').html();

        $('input.treatmentHospitalAddress').val(hospital_address);
        $('input.input_treatmentHospital').val(hospital_name);


    });

    // 获取医生所对应的出诊医院
    function getDoctorHospital(consultantId) {

        // 每次先清空
        $('.treatmentHospital').html('')

        $.ajax({
            async: false,
            cache:false,
            headers: {"Accept-CMS-Token":token},
            type: 'post',
            url: fetchhospitallistbyconsultant,
            data: {
                consultantId:consultantId
            },
            dataType: 'json',
            success: function (data) {
                if(data.resultCode==200) {

                    var list = data.value.list;
                    var len = list.length;

                    for( var i=0;i<len;i++ ){

                        $('select.treatmentHospital').append('<option value="'+list[i].hospitalId+'" address="'+list[i].address+'">'+list[i].name+'</option>');

                    };
                    $('input.treatmentHospitalAddress').val( list[0].address );


                } else if(data.resultCode==515) {

                    reLogin();

                };


            },
            error: function () {
                console.log('预约挂号订单详情获取失败...')
            }
        });

    }

    // 根据后台返回来的状态码...处理订单状态...
    function changRegisOrderStatus( para,life_type ) {

        if(life_type == 1){// 订单进行中

            // 进一步判断订单的状态...
            if( para == 1 ){

                return '抢号中'

            }else if( para == 2 ){

                return '未支付'

            }else if( para == 3 ){

                return '已支付'

            }else if( para == 4 ){

                return '已完成'

            };

        }else if(life_type == 2){//订单已完成

            return '已完成'

        }else if(life_type == 3){//订单已取消

            return '已取消'

        };


    };

    //将支付方式文字化... 1..支付宝,2..微信
    function changePayType( para ) {

        if( para == 1 ){
            return '支付宝';
        }else{
            return '微信';
        };

    };



});
